import React, { useState, useEffect, useMemo } from 'react';
import moment from 'moment'
import { Modal, Skeleton, message, Row, Col } from 'antd'
import {
  ProForm,
  ProFormDatePicker,
  ProFormSelect,
  ProFormRadio,
  ProFormDependency
} from '@ant-design/pro-components';
import type { EditModalProps } from '../data';

import {
  payTypeSchema,
  receiveMethodSchema,
  payStatusSchema
} from '@/utils/schema'


import {
  getOrganizeCreate,
  reqDoctorList,
  reqSchedulingByDoctor
} from '@/services/register';

const PayEditModal: React.FC<EditModalProps> = ({
  row,
  isOpen,
  handleModal,
}) => {

  const formatRow = useMemo(() => {
    // "{"timeSlot":"8:00-9:00","status":1,"originalPrice":15}"
    return {
      tyUserId: row?.tyUserId?.toString(),
      payType: row?.payType ? row?.payType?.toString() : undefined,
      receiveMethod: row?.payType?.toString(),
      status: row?.payType?.toString(),
      appointDate: row?.appointDate,
      timeObj: JSON.stringify({
        timeSlot: '',
        status
      })
    }
  }, [row])

  const title = row?.id ? "修改" : "创建团体账号"
  const [formObj] = ProForm.useForm()
  const [initialValues, setinitialValues] = useState<any>(null)


  const handleEditor = async (params: any) => {
    console.log('handleEditor==== :>> ', params);
    return;
    // const res = await reqUpdateActAnswer({ ...params, id: row?.id })
    // if (res.code == 200) {
    //   message.success(res?.message)
    //   actionRef?.current.reload()
    //   handleModal(false)
    // } else {
    //   message.error(res?.message)
    // }
  }

  useEffect(() => {
    if (row?.id) {
      setinitialValues({
        ...formatRow
      })
    }

    //handleActIdData({});
  }, [])

  async function getAppointTime(reqData: { tyUserId: number, appointDate: string }) {
    if (!reqData?.tyUserId || !reqData?.appointDate) return [];

    const res = await reqSchedulingByDoctor({
      userId: reqData?.tyUserId,
      schedulingDate: moment(reqData?.appointDate).format('YYYY-MM-DD')
    });
    if (res?.resultCode === "00000000") {
      const mapArr = res?.data?.map((item: any) => ({
        value: JSON.stringify(item),
        label: item?.timeSlot,
      }))

      return mapArr
    } else {
      message.error(res?.message)
      return [];
    }
  }

  async function getDocterList() {
    const res = await reqDoctorList({})
    const mapArr = res?.data?.map((item: any) => ({
      value: item?.id,
      label: item?.realName,
    }))

    return mapArr
  }


  return (
    <Modal width={500} title={title} open={isOpen} onCancel={() => handleModal(false)} footer={null} destroyOnClose={true}>
      {
        initialValues === null && row?.id ? <Skeleton active paragraph={{ rows: 6 }} /> :
          <ProForm
            form={formObj}
            initialValues={initialValues}
            onFinish={(values): Promise<any> => handleEditor(values)}>
            <Row gutter={24}>
              <Col span={8}>
                <ProFormSelect
                  request={getDocterList}
                  name="tyUserId"
                  label="选择医生"
                  rules={[
                    {
                      required: true,
                      message: '请选择医生'
                    }
                  ]}
                />
              </Col>
              <Col span={8}>
                <ProFormDependency name={['tyUserId']}>
                  {({ tyUserId }) => {
                    return (
                      <ProFormDatePicker
                        fieldProps={{
                          format: 'YYYY-MM-DD',
                        }}
                        name="appointDate"
                        label="预约日期"
                        disabled={!tyUserId}
                        rules={[
                          {
                            required: true,
                            message: '请选择预约日期'
                          }
                        ]}
                      />
                    );
                  }}
                </ProFormDependency>
              </Col>
              <Col span={8}>
                <ProFormDependency
                  name={['tyUserId', "appointDate"]}
                  shouldUpdate={(prevValues, curValues) => (
                    prevValues.tyUserId !== curValues.tyUserId ||
                    prevValues.appointDate !== curValues.appointDate
                  )}
                >
                  {({ tyUserId, appointDate }) => {
                    return (
                      <ProFormSelect
                        params={{ tyUserId, appointDate }}
                        request={getAppointTime}
                        name="appointtimeObj"
                        label="预约时间"
                        disabled={(!tyUserId || !appointDate)}
                        rules={[
                          {
                            required: true,
                            message: '请选择预约时间'
                          }
                        ]}
                      />
                    );
                  }}
                </ProFormDependency>
              </Col>
              <Col span={24}>
                <ProFormRadio.Group
                  name="payType"
                  label="支付方式"
                  // [1:微信,2:支付宝,3:银行卡,4:现金,5:医保]
                  options={payTypeSchema.options}
                />
              </Col>
              <Col span={24}>
                <ProFormRadio.Group
                  name="receiveMethod"
                  label="取药方式"
                  options={receiveMethodSchema.options}
                />
              </Col>
              <Col span={24}>
                <ProFormRadio.Group
                  name="status"
                  label="订单状态"
                  options={payStatusSchema.options}
                />
              </Col>
            </Row>
          </ProForm>
      }
    </Modal >
  );
};
export { PayEditModal }

